package com.demo.springmvc底层演示.demo5;

import java.util.ArrayList;
import java.util.List;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import com.demo.springmvc底层演示.demo4.User;

// MessageConverter: 返回对象写入http响应；request请求体数据读入对象
public class Test {
	
	public static void main(String[] args) throws Exception {
		test1();
		test2();
		test3();
	}
	
	public static void test1() throws Exception {
		MockHttpOutputMessage message = new MockHttpOutputMessage();
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		if(converter.canWrite(User.class, MediaType.APPLICATION_JSON)) {
			converter.write(new User("张三", 18), MediaType.APPLICATION_JSON, message);
			System.out.println("test1: " + message.getBodyAsString());
		}
	}
	
	public static void test2() throws Exception {
		MockHttpOutputMessage message = new MockHttpOutputMessage();
		MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
		if(converter.canWrite(User.class, MediaType.APPLICATION_XML)) {
			converter.write(new User("李四", 28), MediaType.APPLICATION_XML, message);
			System.out.println("test2: " + message.getBodyAsString());
		}
	}
	
	public static void test3() throws Exception {
		MockHttpServletRequest request = new MockHttpServletRequest();
		MockHttpServletResponse response = new MockHttpServletResponse();
		ServletWebRequest webRequest = new ServletWebRequest(request, response);
		request.addHeader("Accept", "application/xml");
		// 同时指定类型，优先以返回的为准
		response.setContentType("application/json");
		List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>() {{
			add(new MappingJackson2HttpMessageConverter());
			add(new MappingJackson2XmlHttpMessageConverter());
		}};
		RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
		processor.handleReturnValue(new User("张三", 18), new MethodParameter(Test.class.getMethod("user"), -1), new ModelAndViewContainer(), webRequest);
		System.out.println("test3: " + new String(response.getContentAsByteArray(), "utf-8"));
	}
	
	@ResponseBody
	public User user() {
		return null;
	}

}
